package middleware

import (
	"net/http"
	"strings"
	
	"github.com/gin-gonic/gin"
	
	"collecter/app/cache"
	"collecter/app/common/enum"
	"collecter/app/common/helper"
)

func CheckAccessToken() gin.HandlerFunc {
	fn := func(ctx *gin.Context) {
		url := strings.Trim(ctx.Request.URL.Path, "/")
		if len(url) == 0 {
			ctx.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "路由错误", "data": "[]"})
			ctx.Abort()
		}

		accessToken := ctx.Request.Header.Get("X-ACCESSTOKEN")
		// fmt.Println(url, accessToken)
		if len(accessToken) == 0 {
			ctx.JSON(http.StatusInternalServerError, helper.ReturnMsg(4))
			ctx.Abort()
			return
		}
		cacheKey := enum.ACCESS_TOKEN + accessToken
		if cacheToken, err := cache.Cacher.GetString(cacheKey); err != nil || len(cacheToken) == 0 {
			ctx.JSON(http.StatusInternalServerError, helper.ReturnMsg(4))
			ctx.Abort()
			return
		}
	}
	return fn
}
